package cn.com.sassali.dynamic;

import cn.com.sassali.service.IUserService;
import cn.com.sassali.service.impl.UserService;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @ClassName DynamicProxyFactory
 * @Description     动态代理工厂类
 * @Author lujiansen
 * @date 2020/4/26 8:38 下午
 */
public class JdkDynamicProxyFactory {

    public static IUserService userService = new UserService();

    // 通过 Proxy.newProxyInstance 生成代理
    // 使用定义的类 JdkInvocationHandler
    public static IUserService newInstance() {
        JdkInvocationHandler invocationHandler = new JdkInvocationHandler(userService);
        return (IUserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(), userService.getClass().getInterfaces(), invocationHandler);
    }

    // 通过 Proxy.newProxyInstance 生成代理
    // 使用 InvocationHandler 的匿名内部类
    public static IUserService newInstanceByAnonymous() {
        return (IUserService) Proxy.newProxyInstance(userService.getClass().getClassLoader(), userService.getClass().getInterfaces(), new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("开始JDK动态代理 匿名内部类 ===== ");
                Object rlt = method.invoke(userService, args);
                System.out.println("结束JDK动态代理 匿名内部类 ===== ");
                return rlt;
            }
        });
    }

}
